<template>
  <div class="container">
    <TableWrapper
      :title="ntype == 'edit' ? '修改人员' : '新增人员'"
      :offsetX="28"
      :offsetY="12"
    >
      <template #close>
        <el-button
          style="font-size: 26px"
          icon="el-icon-close"
          type="text"
          @click="$emit('close')"
        ></el-button>
      </template>
      <template #header>
        <el-button
          type="primary"
          v-if="'edit' == ntype"
          @click="handleSave('edit')"
          >保存</el-button
        >
        <el-button
          v-if="ntype == 'add'"
          @click="handleSave('add')"
          type="primary"
          plain
          >保存并新增</el-button
        >
      </template>

      <template #main>
        <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
          <div class="chunk">
            <el-divider class="divider" content-position="left">
              <span style="color: #409eff; font-size: 16px">账号信息</span>
            </el-divider>
            <el-row :gutter="gutter" style="margin: 0 40px">
              <el-col :span="6">
                <el-form-item label="员工编号：" prop="userId">
                  <el-input
                    disabled
                    v-model="form.userId"
                    placeholder="员工号是在企业的唯一标识，自动生成"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6" style="display: flex">
                <el-tooltip
                  style="padding-top: 8px"
                  content="员工账号用于进行系统登录账号"
                  placement="top"
                >
                  <i class="el-icon-question"></i>
                </el-tooltip>
                <div style="width: 100%">
                  <el-form-item label="员工账号：" prop="userName">
                    <el-input
                      v-model="form.userName"
                      placeholder="请输入员工账号，不许重复"
                    >
                      <el-select
                        style="width: 75px"
                        v-model="form.sex"
                        slot="append"
                        placeholder=""
                      >
                        <el-option
                          v-for="item in dict.type.sys_user_sex"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        >
                        </el-option>
                      </el-select>
                    </el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="6">
                <el-form-item label="手机号：" prop="phonenumber">
                  <el-input
                    v-model="form.phonenumber"
                    placeholder="请输入手机号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col v-if="ntype != 'edit'" :span="6">
                <el-form-item label="初始密码：" prop="password">
                  <el-input
                    v-model="form.password"
                    placeholder="请输入初始密码"
                  >
                    <el-button
                      style="color: #409eff"
                      slot="append"
                      @click="randomPswd"
                      >随机生成</el-button
                    >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <div class="chunk">
            <el-divider class="divider" content-position="left">
              <span style="color: #409eff; font-size: 16px">组织关系</span>
            </el-divider>
            <el-row :gutter="gutter" style="margin: 0 40px">
              <el-col :span="6">
                <el-form-item label="部门名称：" prop="deptId">
                  <Treeselect
                    v-model="form.deptId"
                    placeholder="请选择部门"
                    :options="deptOptions"
                    :show-count="true"
                  ></Treeselect>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="岗位名称：" prop="postIds">
                  <el-select
                    multiple
                    v-model="form.postIds"
                    placeholder="请选择岗位"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in postTree"
                      :key="item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="所属角色：" prop="roleIds">
                  <el-select
                    ref="selectRef"
                    v-model="form.roleIds"
                    multiple
                    placeholder="请选择角色"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in roleTree"
                      :key="item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入职日期：" prop="dateOfHire">
                  <el-date-picker
                    style="width: 100%"
                    v-model="form.dateOfHire"
                    type="date"
                    placeholder="请选择入职日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="gutter" style="margin: 0 40px">
              <el-col :span="6">
                <el-form-item label="上级领导：" prop="leader">
                  <el-select
                    filterable
                    v-model="form.leader"
                    placeholder="请选择上级领导"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in userTree"
                      :key="item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="人员类型：" personnelType>
                  <el-select
                    v-model="form.personnelType"
                    placeholder="请选择人员类型"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dict.type.sys_personnel_type"
                      :key="item.label + item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div class="chunk">
            <el-divider class="divider" content-position="left">
              <span style="color: #409eff; font-size: 16px">个人信息</span>
            </el-divider>
            <el-row :gutter="gutter" style="margin: 0 40px">
              <el-col :span="6">
                <el-form-item label="身份证号：" prop="idNumber">
                  <el-input
                    v-model="form.idNumber"
                    placeholder="请输入身份证号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="员工姓名：" prop="nickName">
                  <el-input
                    v-model="form.nickName"
                    placeholder="请输入员工姓名，允许重复"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="电子邮箱：" prop="email">
                  <el-input
                    v-model="form.email"
                    placeholder="请输入邮箱地址"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="微信账号：" prop="weChatId">
                  <el-input
                    v-model="form.weChatId"
                    placeholder="请输入微信账号"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="gutter" style="margin: 0 40px">
              <el-col :span="6">
                <el-form-item label="QQ账号：" prop="qqId">
                  <el-input
                    v-model="form.qqId"
                    placeholder="请输入QQ账号"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="出生日期：" prop="birthday">
                  <el-date-picker
                    style="width: 100%"
                    v-model="form.birthday"
                    type="date"
                    placeholder="请选择出生日期"
                    format="yyyy 年 MM 月 dd 日"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="婚姻状况：" prop="maritalStatus">
                  <el-select
                    v-model="form.maritalStatus"
                    placeholder="请选择婚姻状况"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dict.type.sys_marital_status"
                      :key="item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="生育状况：" prop="fertilityStatus">
                  <el-select
                    v-model="form.fertilityStatus"
                    placeholder="请选择生育状况"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dict.type.sys_fertility_status"
                      :key="item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="gutter" style="margin: 0 40px">
              <el-col :span="6">
                <el-form-item label="户口类型：" prop="householdType">
                  <el-select
                    v-model="form.householdType"
                    placeholder="请选择户口类型"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dict.type.sys_household_type"
                      :key="item.value"
                      :label="item.label"
                      :value="parseInt(item.value)"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系地址：" prop="contactAddress">
                  <el-input
                    v-model="form.contactAddress"
                    placeholder="请输入联系地址"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </template>
    </TableWrapper>
  </div>
</template>

<script>
import TableWrapper from "@/components/Table/TableWrapper.vue";
import { generateRandomAlphanumeric } from "@/utils/random.js";
import { getDeptTree } from "@/api/system/dept.js";
import { getNotice, getUserTree, add, update } from "@/api/system/user.js";
import { getpostTree } from "@/api/system/post.js";
import { getRoleTree } from "@/api/system/role.js";
import { v_cardid, v_phone, v_name, v_email } from "@/utils/validate.js";
import {
  getGenderFromIdCard,
  getBirthDateFromId,
} from "@/utils/iDCardUtils.js";

export default {
  dicts: [
    "sys_user_sex",
    "sys_household_type",
    "sys_personnel_type",
    "sys_marital_status",
    "sys_fertility_status",
  ],
  name: "UserInfo",
  components: { TableWrapper },
  props: {
    ntype: {
      type: String,
      default: "add",
    },
    queryId: {
      type: Number,
      required: true,
      default: 0,
    },
  },
  data() {
    return {
      // leyout间隙
      gutter: 30,
      // 详情表数据
      form: {
        nickName: undefined,
        sex: "0",
        password: undefined,
        deptId: undefined,
        roleIds: [],
        dateOfHire: new Date(),
        leader: undefined,
        personnelType: undefined,
        idNumber: undefined,
        userName: undefined,
        email: undefined,
        phonenumber: undefined,
        birthday: undefined,
      },
      // 表单校验结果
      validate: false,
      // 校验规则
      rules: {
        // 员工昵称
        userName: [
          { required: true, message: "请输入员工账号", trigger: "blur" },
        ],
        // 手机号
        phonenumber: [{ required: true, validator: v_phone, trigger: "blur" }],
        // 初始密码
        password: [
          { required: true, message: "请输入初始密码", trigger: "blur" },
        ],
        // 部门
        deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
        // 岗位
        postIds: [{ required: true, message: "请选择岗位", trigger: "blur" }],
        // 所属角色
        roleIds: [
          { required: true, message: "请选择所属角色", trigger: "blur" },
        ],
        // 入职日期
        dateOfHire: [
          { required: true, message: "请选择入职日期", trigger: "blur" },
        ],
        // 上级领导
        leader: [
          { required: true, message: "请选择上级领导", trigger: "blur" },
        ],
        // 人员类型
        personnelType: [
          { required: true, message: "请选择人员类型", trigger: "blur" },
        ],
        // 员工姓名
        nickName: [{ required: true, validator: v_name, trigger: "blur" }],
        // 身份证号
        idNumber: [{ required: true, validator: v_cardid, trigger: "blur" }],
        // 电子邮件
        email: [{ required: true, validator: v_email, trigger: "blur" }],
      },
      // 部门树
      deptOptions: [],
      // 用户树
      userTree: [],
      // 岗位树
      postTree: [],
      // 角色树
      roleTree: [],
    };
  },
  created() {
    // 获取部门树
    getDeptTree().then((res) => {
      this.deptOptions = res.data;
      // 默认选中第一个
      this.form.deptId = res.data[0].id;
    });

    // 获取用户数据
    if (this.ntype == "edit" && this.queryId != 0) {
      getNotice(this.queryId).then((res) => {
        const data = res.data;
        this.form = Object.assign(this.form, data.user);
        this.form.postIds = data.postIds;
        this.form.roleIds = data.roleIds;
      });
    }

    // 获取用户树
    getUserTree().then((res) => {
      this.userTree = res.data;
    });
    // 获取岗位树
    getpostTree().then((res) => {
      this.postTree = res.data;
    });
    // 获取角色树
    getRoleTree().then((res) => {
      this.roleTree = res.data;
    });
  },
  watch: {
    "form.idNumber": function (newVal) {
      if (newVal.length == 18) {
        // 获取性别
        this.form.sex = getGenderFromIdCard(newVal);
        // 获取出生日期
        this.form.birthday = new Date(getBirthDateFromId(newVal));
      }
    },
  },
  methods: {
    // 随机生成初始密码
    randomPswd() {
      this.form.password = generateRandomAlphanumeric(8);
    },
    // 校验表单
    validateForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.validate = true;
          return true;
        } else {
          this.validate = false;
          return false;
        }
      });
    },
    // 添加数据
    handleSave(ntype) {
      // 校验表单
      this.validateForm();

      if (!this.validate) {
        return;
      }

      if (ntype == "add") {
        this.sendAjax(add, this.form);
      } else {
        this.sendAjax(update, this.form);
      }
    },
    // 发送 ajax 请求
    sendAjax(Interface, row) {
      // 调用接口发送请求
      Interface(row).then(
        (res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.msg);
          } else {
            this.$modal.msgError(res.msg);
          }
          this.loading = false;
        },
        () => {
          this.$modal.msgError("系统错误，请稍后尝试！");
        }
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.chunk {
  margin-bottom: 40px;
}

.divider {
  margin-bottom: 50px;
  margin-top: 30px;
}
</style>